package com.mars.algorithm;

/**
 * @Author King
 * @create 2020/7/31 10:51
 */
public class StrPattern {

    public static void main(String[] args) {

        String mainStr = "abghjkuytrdfcvghftuyujgty";
        String c = "ftuyujgty";
        int index = bf(mainStr, c);
        int index2 = bfFind(mainStr, c, c.length());
        System.out.println(index);
        System.out.println(index2);

    }

    private static int bf(String mainStr, String childStr) {
        char[] mainChar = mainStr.toCharArray();
        char[] childChar = childStr.toCharArray();

        if (mainChar.length < childChar.length) {
            return -1;
        }
        int n = mainChar.length;
        int m = childChar.length;
        for (int i = 0; i <= n - m; i++) {
            boolean flag = true;
            for (int j = 0; j < m; j++) {
                if (mainChar[i + j] != childChar[j]) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                return i;
            }
        }
        return -1;
    }


    public static int bfFind(String S, String T, int pos) {
        char[] arr1 = S.toCharArray();
        char[] arr2 = T.toCharArray();
        int i = pos;
        int j = 0;
        while (i < arr1.length && j < arr2.length) {
            if (arr1[i] == arr2[j]) {
                i++;
                j++;
            } else {
                i = i - j + 1;
                j = 0;
            }
        }
        if (j == arr2.length) return i - j;
        else return -1;
    }
}